import * as echarts from '../../ec-canvas/echarts';
import { getAllStudent, getAllCourse, getCourseById } from "../../api/score";

Page({
  data: {
    ec: {
      onInit: null
    },
    scoreList: [],
    editDialogVisible: false,
    currentScore: {},
    courses: [],
    selectedCourse: '', // 选中的课程
    allStudent: [],
    CourseList: [],
    selectedCourseId: '',
    courseNames: [],
    averageScore: 0,
    minScore: 0,
    maxScore: 0,
    scoreCategories: ['0-60', '60-70', '70-80', '80-90', '90-100'],
    scoreData: [0, 0, 0, 0, 0], // 存储每个区间的分数数量
    chart: null // 用于存储echarts实例
  },

  onLoad() {
    this.initECharts();
    const res = getAllStudent();
    const getCourseList = getAllCourse();
    Promise.all([res, getCourseList]).then(([res, getCourseList]) => {
      this.setData({
        allStudent: res.data,
        CourseList: getCourseList.data,
        courses: getCourseList.data.map(course => ({
          name: course.courseName,
          id: course.courseId
        })),
        courseNames: getCourseList.data.map(course => course.courseName)
      });
    });
  },

  initECharts() {
    const that = this; // 保存当前页面的this引用
    this.setData({
      'ec.onInit': function (canvas, width, height, dpr) {
        that.chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(that.chart);
        that.updateChart(); // 初始化图表
        return that.chart;
      }
    });
  },

  updateChart() {
    if (this.chart) {
      this.chart.setOption({
        title: {
          text: '成绩分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: this.data.scoreCategories, // 使用分数区间作为 x 轴数据
          axisLabel: {
            color: '#666'
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#666'
          }
        },
        series: [{
          type: 'bar',
          data: this.data.scoreData, // 使用分数区间的数量作为 y 轴数据
          itemStyle: {
            color: '#37a2da'
          },
          label: {
            show: true,
            position: 'top',
            color: '#666'
          }
        }]
      });
    }
  },

  async onCourseChange(e) {
    const selectedIndex = e.detail.value; // 选中的索引
    const selectedCourse = this.data.courses[selectedIndex]; // 获取选中的课程对象
    this.setData({
      selectedCourse: selectedCourse.name, // 设置显示的课程名称
      selectedCourseId: selectedCourse.id // 保存选中的课程 ID
    });

    // 定时更新数据
    this.fetchAndUpdateData();
    this.startDataRefresh();
  },

  async fetchAndUpdateData() {
    const res = await getCourseById(this.data.selectedCourseId);
    console.log('Course Data:', res); // 检查 API 返回的数据

    // 去重逻辑
    const uniqueScoreList = res.data.filter((item, index, self) =>
      index === self.findIndex((t) => t.studentNo === item.studentNo)
    );
    console.log('Unique Score List:', uniqueScoreList); // 检查去重后的成绩列表

    const scores = uniqueScoreList.map(item => {
      const score = item.score;
      return typeof score === 'number' && !isNaN(score) ? score : 0; // 处理无效分数
    });

    // 统计分数区间
    const scoreData = [0, 0, 0, 0, 0]; // 存储每个区间的分数数量

    scores.forEach(score => {
      if (score >= 0 && score < 60) {
        scoreData[0]++;
      } else if (score >= 60 && score < 70) {
        scoreData[1]++;
      } else if (score >= 70 && score < 80) {
        scoreData[2]++;
      } else if (score >= 80 && score < 90) {
        scoreData[3]++;
      } else if (score >= 90 && score <= 100) {
        scoreData[4]++;
      }
    });

    const averageScore = (array) => {
      const sum = array.reduce((acc, score) => acc + score, 0);
      return (sum / array.length).toFixed(2); // 保留两位小数
    };

    this.setData({
      scoreList: uniqueScoreList,
      averageScore: averageScore(scores),
      minScore: Math.min(...scores),
      maxScore: Math.max(...scores),
      scoreData: scoreData
    }, () => {
      this.updateChart(); // 更新图表
    });
  },

  startDataRefresh() {
    // 每10秒更新一次数据
      this.fetchAndUpdateData();
    
  }
});
